package com.et114.components.rule.support;

import org.drools.RuleBase;
import org.drools.compiler.PackageBuilder;
import org.springframework.core.io.Resource;

import java.io.InputStreamReader;
import java.io.Reader;
import java.util.Iterator;
import java.util.Properties;

/**
 * 
 */
public class DSLRuleBaseLoader extends AbstractFileRuleBaseLoader {
	
	Properties	mappings	= null;
	
	public void setRuleFiles ( Properties mappings ) {
		this.mappings = mappings;
	}
	
	/**
	 * @see org.springside.modules.rule.RuleBaseLoader#buildRuleBase()
	 */
	public RuleBase buildRuleBase ( ) throws Exception {
		java.util.Set keys = mappings.keySet ( );
		for ( Iterator iter = keys.iterator ( ) ; iter.hasNext ( ) ; ) {
			Object key = iter.next ( );
			PackageBuilder builder = new PackageBuilder ( );
			Reader dsl = new InputStreamReader ( getClass ( )
					.getResourceAsStream ( key.toString ( ) ) , "UTF-8" );
			Resource [ ] resources = this.getResources ( mappings
					.getProperty ( key.toString ( ) ) );
			for ( int i = 0 ; i < resources.length ; i ++ ) {
				Resource resource = resources [ i ];
				Reader source = new InputStreamReader ( resource
						.getInputStream ( ) , "UTF-8" );
				builder.addPackageFromDrl ( source , dsl );
			}
			ruleBase.addPackage ( builder.getPackage ( ) );
		}
		
		return ruleBase;
	}
}
